package dao.implementations;

import java.io.Serializable;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import dao.entities.log.LogLine;
import dao.interfaces.ILogFacade;

/**
 * <desc>LogDao are used to persist information in database about the operations
 * of Log </desc> <responsibility>registered all operation in
 * database</responsibility> <coperation>Implements
 * LogOperationFacade</coperation>
 * 
 * @version 0.1 Create 18-03-2009 Author Alfred Oliver
 */
@SuppressWarnings("serial")
public class LogJPAHibernate implements Serializable, ILogFacade {

	/** Field with database connection */
	private EntityManager entManager;

	private static LogJPAHibernate logManager = null;;

	/** State debug */
	private boolean enabled = true;

	/**
	 * PRIVATE Constructor of class LogDao. It should be Singleton pattern
	 * 
	 * @throws DataException.
	 * @param pConnect
	 *            . Connection database.
	 * @param pProgram
	 *            . Work program.
	 */
	private LogJPAHibernate(String logManagerName, boolean enabled) {

		this.enabled = enabled;
		if (this.enabled) {
			EntityManagerFactory factory;
			try {

				factory = Persistence
						.createEntityManagerFactory(logManagerName);
				entManager = factory.createEntityManager();

			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	}

	/**
	 * Get SINGLETON object
	 */

	public static ILogFacade getLogManager(String LogMangerName, boolean enabled) {
		if (logManager == null) {
			logManager = new LogJPAHibernate(LogMangerName, enabled);
		}
		return logManager;
	}

	public void saveLog(LogLine logLine) {
		if (this.enabled) {
			try {
				entManager.getTransaction().begin();
				entManager.persist(logLine);
				entManager.getTransaction().commit();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	@Override
	public void enableLog(Boolean enabled) {
	}

}
